#include "handleloginrequest.h"


HandleLoginRequest::HandleLoginRequest(const QString& dbPath, QObject *parent)
    : QObject(parent),  m_dbPath(dbPath) {
}

HandleLoginRequest::~HandleLoginRequest() {

}

QString HandleLoginRequest::hashPassword(const QString &tempPassword) {
    return QString(QCryptographicHash::hash(tempPassword.toUtf8(), QCryptographicHash::Sha256).toHex());
}

void HandleLoginRequest::LoginVerification(const QString &tempUsername, const QString &tempPassword, QTcpSocket *socket) {
    // 为每个线程生成唯一的连接名
    QString connName = QString("login_%1").arg(quintptr(QThread::currentThreadId()));
     // 限定数据库对象作用域
    bool result;
    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connName); // 创建独立连接
        db.setDatabaseName(m_dbPath);
        db.setConnectOptions("QSQLITE_BUSY_TIMEOUT=2000");
        if (!db.open()) {
            qDebug() << "Database open failed:" << db.lastError().text();
            emit isLoginVerification(false, socket);
            return;
        }
        // 显式绑定到当前连接
        QSqlQuery query(db);
        query.prepare("SELECT * FROM users WHERE username = :username AND password = :password");
        query.bindValue(":username", tempUsername);
        query.bindValue(":password", hashPassword(tempPassword));

        if (!query.exec() || !query.next()) {
            result = false;
        } else {
            result = true;
        }
        query.finish();
    }

    // 安全移除连接
    if (QSqlDatabase::contains(connName)) {
        QSqlDatabase::removeDatabase(connName);
    }
    emit isLoginVerification(result, socket);
}

